package com.cloudcentral.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudcentral.entity.PCM;
import com.cloudcentral.exception.FailureException;
import com.cloudcentral.mapper.PCMMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;

/**
 * <p>
 * PCM探测记录表 服务实现类
 * </p>
 *
 * @author Administrator
 * @since 2023-11-23
 */
@Slf4j
@Service
public class PCMService extends ServiceImpl<PCMMapper, PCM> {
  @Transactional(rollbackFor = {Exception.class})
  @GlobalTransactional(rollbackFor = {Exception.class})
  public Boolean submit(JSONObject json) throws Exception {
    PCM pcm = PCM.builder().pcm(json.getString("pcm")).build();
    json.remove("pcm");
    Date reportTime = json.getDate("report_time");
    if (reportTime != null) {
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(reportTime);
      if (json.containsKey("detect_id")) calendar.set(Calendar.SECOND, 0);
      pcm.setReportTime(calendar.getTime());
      json.remove("report_time");
    }
    pcm.setData(json.toJSONString());
    if (StringUtils.isBlank(pcm.getPcm())) throw new FailureException("缺少PCM数据流");
    else if (StringUtils.isBlank(pcm.getData())) throw new FailureException("缺少数据字段");
    else return save(pcm);
  }
}
